from grid_env_ideal_obs_repeat_task import *
from grid_agent import *
from checkpoint_utils import *
from maze_factory import *
from replay_config import *
import argparse
import json
import sys
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.lines import Line2D
from sklearn.manifold import TSNE
import random
from sklearn.decomposition import PCA
from matplotlib.animation import FuncAnimation
from sklearn.cluster import KMeans
import threading
import mplcursors
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

def progress_bar(current, total, barLength = 100):
    percent = float(current) * 100 / total
    arrow = '-' * int(percent/100 * barLength - 1) + '>'
    spaces = ' ' * (barLength - len(arrow))

    print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')
    sys.stdout.flush()

@partial(jax.jit, static_argnums=(3,))
def model_forward(variables, state, x, model):
    """ forward pass of the model
    """
    return model.apply(variables, state, x)

@jit
def get_action(y):
    return jnp.argmax(y)
get_action_vmap = jax.vmap(get_action)

# load landscape and states from file
def load_task(pth = "./logs/task.json", display = True):
    # open json file
    with open(pth, "r") as f:
        data = json.load(f)
        landscape = data["data"]
        state = data["state"]
        goal = data["goal"]
        if display:
            print("state: ", state)
            print("goal: ", goal)
            print("landscape: ", landscape)
    return landscape, state, goal


def main():

    seq_len = 32

    """ parse arguments
    """
    rpl_config = ReplayConfig()

    parser = argparse.ArgumentParser()
    parser.add_argument("--model_pth", type=str, default=rpl_config.model_pth)
    parser.add_argument("--map_size", type=int, default=rpl_config.map_size)
    parser.add_argument("--task_pth", type=str, default=rpl_config.task_pth)
    parser.add_argument("--log_pth", type=str, default=rpl_config.log_pth)
    parser.add_argument("--nn_size", type=int, default=rpl_config.nn_size)
    parser.add_argument("--nn_type", type=str, default=rpl_config.nn_type)
    parser.add_argument("--show_kf", type=str, default=rpl_config.show_kf)
    parser.add_argument("--visualization", type=str, default=rpl_config.visualization)
    parser.add_argument("--video_output", type=str, default=rpl_config.video_output)
    parser.add_argument("--life_duration", type=int, default=rpl_config.life_duration)

    args = parser.parse_args()

    rpl_config.model_pth = args.model_pth
    rpl_config.map_size = args.map_size
    rpl_config.task_pth = args.task_pth
    rpl_config.log_pth = args.log_pth
    rpl_config.nn_size = args.nn_size
    rpl_config.nn_type = args.nn_type
    rpl_config.show_kf = args.show_kf
    rpl_config.visualization = args.visualization
    rpl_config.video_output = args.video_output
    rpl_config.life_duration = args.life_duration

    nn_type = ''
    if rpl_config.nn_type == "vanilla":
        nn_type = "vanilla"
    elif rpl_config.nn_type == "gru":
        nn_type = "gru"

    """ load task
    """
    landscapes, states, goals = [], [], []
    rf_task_file = "./data/rf_pass_task_"+nn_type+".txt"
    rf_task_list = []
    for line in open(rf_task_file):
        rf_task_list.append(line.strip())
    print("len of tf_task_list: ", len(rf_task_list))
    # print("tf_task_list: ", tf_task_list)
    dir_path = "./data/adaptive_trajectory_optimization/task_envs/"
    for tt in rf_task_list:
        # get complete path
        task_pth = dir_path + str(tt)
        landscape, state, goal = load_task(task_pth, display=False)

        landscapes.append(landscape)
        states.append(state)
        goals.append(goal)

    num_envs = len(landscapes)

    states = jnp.array(states)
    goals = jnp.array(goals)

    print("shape of states: ", states.shape)
    print("shape of goals: ", goals.shape)

    """ load model
    """
    params = load_weights(rpl_config.model_pth)
    
    """ create agent
    """
    if rpl_config.nn_type == "vanilla":
        model = RNN(hidden_dims = rpl_config.nn_size)
    elif rpl_config.nn_type == "gru":
        model = GRU(hidden_dims = rpl_config.nn_size)

    # check if param fits the agent
    if rpl_config.nn_type == "vanilla":
        assert params["params"]["Dense_0"]["kernel"].shape[0] == rpl_config.nn_size + 10

    """ create grid env
    """
    start_time = time.time()
    GE = GridEnv(landscapes = landscapes, width = 12, height = 12, num_envs_per_landscape = 1, reward_free=True)
    GE.reset()
    print("time taken to create envs: ", time.time() - start_time)

    # set states of GE
    GE.batched_states = states.copy()
    # set goals of GE
    GE.batched_goals = goals.copy()
    GE.init_batched_states, GE.init_batched_goals = jnp.copy(GE.batched_states), jnp.copy(GE.batched_goals)
    GE.batched_goal_reached = batch_compute_goal_reached(GE.batched_states, GE.batched_goals)
    GE.last_batched_goal_reached = jnp.copy(GE.batched_goal_reached)
    GE.concat_obs = get_ideal_obs_vmap(GE.batched_envs, GE.batched_states, GE.batched_goals, GE.last_batched_goal_reached)
    concat_obs = GE.concat_obs
    
    arrow_length = 1
    arrow_list = np.array([[arrow_length, 0], [-arrow_length, 0], [0, arrow_length], [0, -arrow_length], [0, 0]])

    # 生成一个二进制串集合，其中每个元素都是一个长度为8的二进制串，要求这些二进制串从 000000000 遍历到 111111111
    binary_set = set()
    for i in range(256):
        binary_string = format(i, '08b')
        binary_set.add(binary_string)
    # 将 binary_set 中的 11111111 元素删除
    binary_set.remove("11111111")
    # 将 binary_set 中所有格式为 "x1x1x1x1" 的元素删除
    binary_set_bk = binary_set.copy()
    for binary in binary_set_bk:
        if binary[1] == '1' and binary[3] == '1' and binary[4] == '1' and binary[6] == '1':
            binary_set.remove(binary)
    print("binary_set: ", binary_set)
    
    # 对 binary_set 进行排序，使得其中的元素从 00000000 遍历到 11111110
    binary_list = sorted(binary_set)
    # 将 binary_list 中的每个元素进行这样的操作：在中间插入一个0，例如 "00000000" 转换为 "000000000"；然后在结尾处插入一个0，例如 "000000000" 转换为 "0000000000"
    binary_list = [i[:4] + "0" + i[4:] + "0" for i in binary_list]
    # 将 binary_list 中的元素转换为整数数组，例如 "00000000" 转换为 [0, 0, 0, 0, 0, 0, 0, 0]
    binary_list = [list(map(int, list(i))) for i in binary_list]
    binary_list = np.array(binary_list)
    print("shape of binary_list: ", binary_list.shape)

    binary_list, arrow_list = np.array(binary_list), np.array(arrow_list)

    def make_obs_img(obs_int):
        # 将形状为 (10,) 的 obs 裁减掉最后一位，变成形状为 (9,) 的 obs
        obs = obs_int[:-1]
        # 将 obs 转换为形状为 (3, 3) 的 numpy 数组
        obs = obs.reshape((3, 3))
        
        # 将 obs 中的 1 替换为 255
        obs = (1-obs) * 255
        # 将 obs 转换为形状为 (3, 3, 1) 的 numpy 数组
        obs = obs.reshape((3, 3, 1))
        # 将 obs 转换为形状为 (3, 3, 3) 的 numpy 数组
        obs = np.concatenate((obs, obs, obs), axis=2)
        # 将 obs 转换为 opencv 的8比特图像格式
        obs = obs.astype(np.uint8)
        # 将 obs 转换为形状为 (60, 60, 3) 的 numpy 数组
        obs = cv2.resize(obs, (60, 60), interpolation=cv2.INTER_NEAREST)
        # 在 obs 上绘制 3x3 的灰色网格
        for i in range(1, 3):
            cv2.line(obs, (0, i*20), (60, i*20), (100, 100, 100), 1)
            cv2.line(obs, (i*20, 0), (i*20, 60), (100, 100, 100), 1)
        # 在 obs 的边缘绘制灰色边框
        cv2.rectangle(obs, (0, 0), (59, 59), (100, 100, 100), 1)
        return obs

    trajectories = []
    goal_reached = []
    obs_record = []
    neural_states = []
    action_record = []

    rnn_state = model.initial_state(GE.num_envs)

    rkey = jax.random.PRNGKey(np.random.randint(0, 1000000))

    for t in range(rpl_config.life_duration):

        progress_bar(t, rpl_config.life_duration)

        """ model forward and step the env
        """
        rnn_state, y1 = model_forward(params, rnn_state, concat_obs, model)
        batched_actions = get_action_vmap(y1)
        batched_goal_reached, concat_obs = GE.step(batched_actions, reset=False)

        trajectories.append(np.array(GE.batched_states))
        obs_record.append(np.array(concat_obs))
        action_record.append(np.array(batched_actions))

    trajectories = np.array(trajectories)
    obs_record = np.array(obs_record)
    action_record = np.array(action_record)

    trajectories = np.swapaxes(trajectories, 0, 1)
    obs_record = np.swapaxes(obs_record, 0, 1)
    action_record = np.swapaxes(action_record, 0, 1)

    print("shape of trajectories: ", trajectories.shape)
    print("shape of obs_record: ", obs_record.shape)
    print("shape of action_record: ", action_record.shape)

    # # 将 goal_reached、trajectories、obs_record、neural_states 保存到文件中
    # np.save("./logs/goal_reached.npy", goal_reached)
    # np.save("./logs/trajectories.npy", trajectories)
    # np.save("./logs/obs_record.npy", obs_record)
    # np.save("./logs/neural_states.npy", neural_states)

    # 载入 er9 数据
    er9_data = np.load("./logs/e_r9_data_gru.npz")
    er9_rnn_state_trajectory_set = er9_data["rnn_state_trajectory_set"]
    er9_tracelet_slices1 = er9_data["tracelet_slices1"]
    er9_tracelet_slices2 = er9_data["tracelet_slices2"]
    er9_tracelet_slices3 = er9_data["tracelet_slices3"]
    er9_tracelet_slices4 = er9_data["tracelet_slices4"]
    er9_tracelet_slices5 = er9_data["tracelet_slices5"]
    er9_seq_len = er9_data["seq_len"]
    er9_collect_capacity = er9_data["collect_capacity"]

    er9_tracelets = [er9_tracelet_slices1[0], er9_tracelet_slices2[0], er9_tracelet_slices3[0], er9_tracelet_slices4[0], er9_tracelet_slices5[0]]
    er9_tracelets = np.array(er9_tracelets)
    print("shape of er9_tracelets: ", er9_tracelets.shape)

    rnd_er9_tracelet_id = np.random.randint(0, er9_tracelets.shape[0])
    chosen_er9_tracelet = er9_tracelets[rnd_er9_tracelet_id]

    """ 从 trajectories 中筛选符合标准的路径片段
        1. 路径的长度等于 seq_len
        2. 起点到终点的hamming距离不小于 seq_len/redundancy
        3. 路径上没有重复位置的点(没有无效action)
    """
    redundancy = 3
    tracelet_slices = []
    obs_slices = []
    action_slices = []
    for t in range(trajectories.shape[0]):
        
        progress_bar(t, trajectories.shape[0])

        qc_pass = False
        tracelet = trajectories[t]
        obs = obs_record[t]
        action = action_record[t]
        # 1. 路径的长度等于 seq_len
        for i in range(tracelet.shape[0]-seq_len+1):
            tracelet_slice = tracelet[i:i+seq_len]
            obs_slice = obs[i:i+seq_len]
            action_slice = action[i:i+seq_len]
            # 2. 起点到终点的hamming距离不小于 seq_len/2
            if seq_len >= np.sum(np.abs(tracelet_slice[0] - tracelet_slice[-1]))*redundancy:
                # 3. 路径上没有相邻位置重复位置的点(没有无效action)
                NEA = False
                for j in range(seq_len-1):
                    if np.sum(np.abs(tracelet_slice[j] - tracelet_slice[j+1])) == 0:
                        NEA = True
                        break
                if not NEA:
                    tracelet_slice_reg = tracelet_slice - tracelet_slice[0]
                    chosen_er9_tracelet_reg = chosen_er9_tracelet - chosen_er9_tracelet[0]
                    if tracelet_slice_reg[-1,0] == chosen_er9_tracelet_reg[-1,0] and tracelet_slice_reg[-1,1] == chosen_er9_tracelet_reg[-1,1]:
                        qc_pass = True
                        break

        if qc_pass:
            tracelet_slices.append(tracelet_slice)
            obs_slices.append(obs_slice)
            action_slices.append(action_slice)

    tracelet_slices = np.array(tracelet_slices)
    obs_slices = np.array(obs_slices)
    action_slices = np.array(action_slices)

    print("shape of tracelet_slices: ", tracelet_slices.shape)
    print("shape of obs_slices: ", obs_slices.shape)
    print("shape of action_slices: ", action_slices.shape)

    rnd_idx = np.random.randint(0, tracelet_slices.shape[0])

    # rnd_idx = 3176

    print("rnd_idx: ", rnd_idx)

    # # 将 obs_slices[rnd_idx] 的所有元素绘制出来，并且拼接成一张大图
    # obs_slices_img = []
    # for i in range(obs_slices[rnd_idx].shape[0]):
    #     obs_slices_img.append(make_obs_img(obs_slices[rnd_idx][i]))
    # # 将 obs_slices_img 中的所有图像拼接成一张大图
    # obs_slices_img = np.concatenate(obs_slices_img, axis=1)
    # cv2.imshow("obs_slices_img", obs_slices_img)
    # cv2.waitKey(0)

    # # 将 tracelet_slices[rnd_idx] 绘制到一个plot中显示出来
    # x = tracelet_slices[rnd_idx][:,0]
    # y = tracelet_slices[rnd_idx][:,1]

    # fig, ax1 = plt.subplots(figsize=(12, 12))

    # # 在第一个子图中绘制散点图和连线
    # ax1.scatter(x, y, s=80)
    # for i, (xi, yi) in enumerate(zip(x, y)):
    #     ax1.text(xi, yi, str(i), ha='left', va='bottom', fontsize=20)
    # ax1.plot(x, y, '-')
    # # 同时用红色 plot 绘制 chosen_er9_tracelet
    # chosen_er9_tracelet_reg = chosen_er9_tracelet+tracelet_slices[rnd_idx][0]
    # ax1.plot(chosen_er9_tracelet_reg[:,0], chosen_er9_tracelet_reg[:,1], '-', color='red')

    # ax1.set_xlim(0, 11)
    # ax1.set_ylim(0, 11)
    # ax1.set_title('Scatter Plot of Coordinates')
    # ax1.set_xlabel('X')
    # ax1.set_ylabel('Y')

    # plt.show()

    # 保存 chosen_er9_tracelet 和 tracelet_slices[rnd_idx] 和 rnd_idx 到npz文件中
    np.savez("./logs/tracelet_slices_and_chosen_er9_tracelet.npz", 
             tracelet_slices=tracelet_slices[rnd_idx], 
             chosen_er9_tracelet=chosen_er9_tracelet, 
             rnd_idx=rnd_idx)



if __name__ == "__main__":
    main()